package cn.cjlmonster.demo02.ui;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import cn.cjlmonster.demo02.Configs;
import cn.cjlmonster.demo02.MainActivity;
import cn.cjlmonster.demo02.R;
import cn.cjlmonster.demo02.adapter.LanguageAdapter;
import cn.cjlmonster.demo02.base.BaseAppCompatActivity;
import cn.cjlmonster.demo02.utils.SPUtils;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/20 5:34 下午.
 */
public class LanguageSettingsActivity extends BaseAppCompatActivity implements LanguageAdapter.OnItemSelectedListener {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_language_settings;
    }

    @Override
    protected boolean canBack() {
        return true;
    }

    private RecyclerView recyclerView;

    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.addItemDecoration(new DividerItemDecoration(this, RecyclerView.VERTICAL));
    }

    private final static String[] language_codes = {"sys", "zh_CN", "zh_TW", "en"};

    private int current_index;

    @Override
    protected void initData() {
        String[] languages = getResources().getStringArray(R.array.language_arrays);
        current_index = SPUtils.getInstance().getInt(Configs.CURRENT_LANGUAGE_INDEX, 0);

        LanguageAdapter adapter = new LanguageAdapter(this, languages, current_index);
        adapter.setOnItemSelectedListener(this);

        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemSelected(LanguageAdapter adapter, int position, String language) {
        if (position != current_index) {
            current_index = position;
            SPUtils.getInstance().putInt(Configs.CURRENT_LANGUAGE_INDEX, current_index);
            SPUtils.getInstance().putString(Configs.CURRENT_LANGUAGE, language_codes[current_index]);
            adapter.changeIndex(current_index);

            sendReStartEvent(MainActivity.class);
        }
    }
}
